package com.kuang.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author luomingliang
 * @date 2021/5/12 21:26
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        // 并发：多线程操作同一个资源类，把资源丢入线程
        Ticket2 ticket = new Ticket2();
        Runnable runnable = () -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        };
        new Thread(runnable, "A").start();
        new Thread(runnable, "B").start();
        new Thread(runnable, "C").start();
    }
}

//Lock三部曲
//1.new ReentrantLock();
//2.lock.lock();
//3.lock.unlock();
class Ticket2 {
    //属性 方法
    private int num = 30;

    Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock(); //加锁
        try {
            //业务代码
            if (num > 0) {
                System.out.println(Thread.currentThread().getName()+"买了一张票，剩余"+(--num));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock(); //解锁
        }
    }
}
